package com.mark.flutterhybridandroid.messageChannel;

import android.app.Activity;
import android.widget.Toast;

import com.mark.flutterhybridandroid.IShowMessage;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.view.FlutterView;

/**
 * @Desc MethodChannelPlugin
 * 用于传递方法调用（method invocation），一次性通信，通常用于Dart调用Native的方法：如拍照；
 * @作者 Mark
 * @时间 2019-04-26
 * @EMail 2285581945@qq.com
 */
public class MethodChannelPlugin implements MethodChannel.MethodCallHandler {
    private final Activity activity;

    private MethodChannelPlugin(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(FlutterView flutterView) {
        MethodChannel channel = new MethodChannel(flutterView, "MethodChannelPlugin");
        MethodChannelPlugin instance = new MethodChannelPlugin((Activity) flutterView.getContext());
        channel.setMethodCallHandler(instance);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        switch (methodCall.method) {
            case "send":
                showMessage(methodCall.arguments());
                break;
            default:
                result.notImplemented();
        }
    }

    /**
     * 展示来自Dart的数据
     *
     * @param arguments
     */
    private void showMessage(String arguments) {
        if (activity instanceof IShowMessage){
            ((IShowMessage)activity).onShowMessage(arguments);
        }
        Toast.makeText(activity,arguments,Toast.LENGTH_SHORT).show();
    }
}
